package com.red.star.wechat.data.repository;

import com.red.star.wechat.data.core.constant.MongoConstant;
import com.red.star.wechat.data.entity.ChatMessage;
import com.red.star.wechat.data.entity.OfflineMessage;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/**
 * @author nofish.yan@gmail.com
 * @date 2018/2/5.
 * 离线消息数据访问类
 */
@Repository
public class ChatOfflineMessageRepository {

    @Resource
    private MongoTemplate mongoTemplate;

    public int saveFansOfflineMessage(Integer fansId, ChatMessage message) {
        Query query = Query.query(Criteria.where("fans_id").is(fansId));
        Update update = new Update();
        update.push("messages", message);
        int n = mongoTemplate.upsert(query, update, OfflineMessage.class, MongoConstant.COLLECTION_NAME_OF_CHAT_OFFLINE).getN();
        return n;
    }

    public int saveAdminOfflineMessage(Integer adminId, ChatMessage message) {
        Query query = Query.query(Criteria.where("admin_id").is(adminId));
        Update update = new Update();
        update.push("messages", message);
        int n = mongoTemplate.upsert(query, update, OfflineMessage.class, MongoConstant.COLLECTION_NAME_OF_CHAT_OFFLINE).getN();
        return n;
    }

    public OfflineMessage findOfflineMessage(Integer fansId) {
        Query query = Query.query(Criteria.where("fans_id").is(fansId));
        return mongoTemplate.findOne(query, OfflineMessage.class, MongoConstant.COLLECTION_NAME_OF_CHAT_OFFLINE);
    }

    public int removeOfflineMessage(Integer fansId) {
        Query query = Query.query(Criteria.where("fans_id").is(fansId));
        return mongoTemplate.remove(query, OfflineMessage.class, MongoConstant.COLLECTION_NAME_OF_CHAT_OFFLINE).getN();
    }
}
